# -*- coding: UTF-8 -*-

from types import *

from Cheetah.Template import Template

from database import getTabList

from utils import makedir

import os
import sys
import re

class createList:  
  
  def __init__(self):
    self.tables = []
    self.packages = ['hibernate','module', 'test']
    self.dirs = ['action', 'business', 'form', 'orm']
    self.base = os.getcwd()
    self.project = "Kylin"
    self.project_path = self.base+"\\"+self.project
    self.src = self.project_path+"\\src"
    self.module_base = self.src + "\\com\\Kylin\\module\\"
    self.test_base = self.src + "\\com\\Kylin\\test\\"
    makedir.makedir()
    print "init... "
    
  def setTables(self, tables):
      self.tables = tables

  def code(self, table, part):
    pass
  
  def actionCode(self, table):
    Table = self.getCap(table)
    sqloutput = open(self.module_base+table.replace("_","") +"\\action\\"+Table+"Action.java", 'w') 
    Table = self.getCap(table)
    nameSpace = {'table':table, 'Table':Table}     
    sp = Template(file="mod_template\\action\\Action.java", searchList=[nameSpace])
    sp = "%s"%(sp)
    sqloutput.writelines(sp)

  def hibernatecfg(self):
    tables = []
    for table in self.tables:
      tab = {}
      tab['table'] =  table
      tab['cname'] = table.replace("_","")
      tab['Table'] = self.getCap(table)
      tables.append(tab)
   
    output = open(self.src+"\\com\\Kylin\\hibernate\\hibernate.cfg.xml", 'w') 
    nameSpace = {'tables':tables}     
    sp = Template(file="mod_template\\hibernate.cfg.xml", searchList=[nameSpace])
    sp = "%s"%(sp)
    output.writelines(sp)
    
    
  def businessCode(self):
    pass
    
  def formCode(self):
    pass
    
  def ormCode(self,table):
    fields = getTabList.getColumns(table)
    print ">>>>>>>>>>>>>"
    print table
    Table = self.getCap(table)
    PTable = [] #{}
    propertys = []
    #print self.getCap(table)
    dict = {}
    for row in fields:
      #print self.getMapping(row['Type'])
      property ={}
      str = row['Field']
      
      if str.find('fk_') == 0:
        pclass = {}
        
        fk = self.getParentTable(str)
        if fk in dict:
          dict[fk] = dict[fk] + 1          
        else:
          dict[fk] = 1
        
        pclass['name'] = fk.replace("_","")
        pclass['table'] = fk
        #pclass['cname'] = 
        pclass['class'] = self.getCap(fk)
        pclass['column'] = str
        #print dict[fk]
        if dict[fk] == 1:
          pclass['seq'] = ""
        else:
          pclass['seq'] = dict[fk]
        
        PTable.append(pclass)
        
      elif str.find('pk_') == 0:
        pk = str
      else:
        #print row['Field']
        property['col'] = row['Field']
        property['name'] = row['Field'].replace("_","")
        property['type'] = self.getMapping(row['Type'])
        property['length'] = 16
        property['null'] = 'null'
        propertys.append(property)
   
    jtable = table.replace("_","")
    
    pathout = self.module_base+jtable +"\\orm\\"+Table+".hbm.xml"
    pathin ="mod_template\\orm\\Member.hbm.xml"
    self.output(pathin, pathout,table,Table,pk,PTable,propertys)
    ##############################################################################
    pathout = self.module_base+jtable +"\\orm\\"+Table+".java"
    pathin="mod_template\\orm\\pojo.java"
    self.output(pathin, pathout,table,Table,pk,PTable,propertys)

    ##############################################################################
    pathout = self.module_base+jtable +"\\orm\\"+Table+"DAO.java"
    pathin="mod_template\\orm\\DAO.java"
    self.output(pathin, pathout,table,Table,pk,PTable,propertys)

    ##############################################################################
    pathout = self.test_base+"Test"+Table+".java"
    pathin="mod_template\\test\\Test.java"
    self.output(pathin, pathout,table,Table,pk,PTable,propertys)
    
    ##############################################################################
    pathout = self.module_base+jtable+"\\form\\"+Table+"Form.java"
    pathin="mod_template\\form\\Form.java"
    self.output(pathin, pathout,table,Table,pk,PTable,propertys)
    
    ##############################################################################
    pathout = self.module_base+jtable+"\\business\\"+Table+"BusinessBean.java"
    pathin ="mod_template\\business\\Business.java"
    self.output(pathin, pathout,table,Table,pk,PTable,propertys)
    
    ##############################################################################    

  
  def output(self,pathin, pathout,table,Table,pk,PTable,propertys):
    """
    output = open(pathout, 'w')     
    nameSpace = {'table':table,'Table':Table,'pk': pk ,'PTable':PTable, 'propertys':propertys}       
    sp = Template(file=pathin, searchList=[nameSpace])
    sp = "%s"%(sp)
    output.writelines(sp)
    """
    print "output..."
    
  def getCap(self, word):
    
    wordlist = word.split('_')
    #print wordlist,
    if 1 == len(wordlist):
      return word.capitalize()
    else:
      y = ""
      for x in wordlist:
        y += x.capitalize()
      return y
      
    #return cap
  
  
  def getParentTable(self, word):
    #print word
    wordlist = word.split('_')
    y = ""
    for x in range(1,len(wordlist)-1):
      y  += wordlist[x]+'_'
    return y.strip('_')
  
  def getMapping(self, coltype):
    ttype  = coltype.split('(')
    
    rawstr = r"""\((.*)\)"""
    compile_obj = re.compile(rawstr)
    match_obj = compile_obj.search(coltype)
    length = 0
    if match_obj:
      all_groups = match_obj.groups()
      length = match_obj.group(1)
      if length.find(','):
        lth = length.split(',')
        length = lth[0]
    
    if len(ttype) == 1:
      dtype = coltype
    else:
      dtype = ttype[0]      
    
    if dtype == 'bigint':  
      jtype = 'java.lang.Long'
      stype = 'Long'
      tvalue = '10L'

    elif dtype == 'int':
      jtype = 'java.lang.Integer'
      stype = 'Integer'
      tvalue = '9'
    elif dtype == 'varchar':
      jtype = 'java.lang.String'
      stype = 'String'
      tvalue = '"test"'

    elif dtype == 'datetime':  
      jtype = 'java.util.Date'
      stype = 'Date'
      tvalue = 'new Date()'
    elif dtype == 'date':  
      jtype = 'java.util.Date' 
      stype = 'Date' 
      tvalue = 'new Date()'
    elif dtype == 'text':  
      jtype = 'java.lang.String'      
      stype = 'String'
      tvalue = '"test again"' 
    elif dtype == 'tinyint':  
      jtype = 'java.lang.Short'
      stype = 'Short'
      tvalue = '1'
    elif dtype == 'decimal':  
      jtype = 'java.lang.Double'      
      stype = 'Double'      
      tvalue = '10.26'
    else:
      print dtype
      print "============================================"
      print "please add new type"
      sys.exit(0)
    typedict= {}
    typedict['longtype'] = jtype
    typedict['shorttype'] = stype
    typedict['length'] = length
    typedict['value'] = tvalue
    
    #print coltype,jtype,stype
    
    return typedict
    #return jtype
    
  def mkdir(self, path):
    if not os.path.exists(path):
      #print "make dir"
      os.mkdir(path)
      
  def makedir(self):
    #com.kylin.module.address.action
    # dir list: action, business, form, orm,    
    #path = os.getcwd()
    
    self.mkdir(self.project_path)
    
    src = self.src
    self.mkdir(src)
    pstr = "com.kylin"
    pathlist = pstr.split('.')
    #print pathlist
    for x in pathlist:
      src = src+"\\"+x
      self.mkdir(src)
    for y in self.packages:
      path = src+"\\"+y
      self.mkdir(path)
    #self.base = src
    
  def run(self):
    #generate hibernate configure file
    self.hibernatecfg()
    src =  self.src
    for tab in self.tables:
      objdir = src + "\\com\\Kylin\\module\\" +tab.replace("_","")
      self.mkdir(objdir)
      for sub in self.dirs:
        subdir = objdir +"\\" +sub
        self.mkdir(subdir)
        #self.code(x, y)
      #self.actionCode(x)
      self.ormCode(tab)
    
    
  def __del__(self):
    pass
    #input.close()
    
def main():
    tabs = getTabList.gettables()
    d = createList()
    d.setTables(tabs)
    d.makedir()
    d.run()


if __name__ == "__main__":
  main()
